package com.cc.shriojwtredis.wanling.config;
import com.cc.shriojwtredis.wanling.mapper.UserMapper;
import com.cc.shriojwtredis.wanling.po.JWTToken;
import com.cc.shriojwtredis.wanling.utils.TokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @ Program       :  com.cqie.wanling.filter.JWTFilter
 * @ Description   :  自定义Realm，实现Shiro认证
 * @ Author        :  cc
 * @ CreateDate    :  2024-4-16
 */
@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("用户授权");
        // 获取用户名，这里直接从PrincipalCollection中获取，而不是使用TokenUtil.getAccount(principalCollection.toString())
        Object principal = principalCollection.getPrimaryPrincipal();
        if (!(principal instanceof String)) {
            throw new IllegalArgumentException("Unexpected principal type: " + principal.getClass());
        }
        String username = (String) principal;
        System.out.println("++++++++JWTToken+++++++++++");
        int myRole=userMapper.getUserByAccount(username).getRole();
        System.out.println(myRole);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (myRole==1) {
            Set<String> role = new HashSet<>();
            role.add("管理员");
            info.setRoles(role);
        } else if(myRole==2){
            Set<String> role = new HashSet<>();
            role.add("供应商");
            info.setRoles(role);
        }else if(myRole==3){
            Set<String> role = new HashSet<>();
            role.add("采购方");
            info.setRoles(role);
        }
        return info;
    }

    /**
     * 用户身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份认证");
        String rawToken = (String) authenticationToken.getCredentials();
        String token = rawToken.startsWith("Bearer ") ? rawToken.substring(7) : rawToken; // 移除"Bearer "前缀
        System.out.println("*******************");
        System.out.println(TokenUtil.getCurrentTime(token));
        System.out.println(TokenUtil.getAccount(token));
        // 使用TokenUtil.getAccount(token)获取用户名
        String username = TokenUtil.getAccount(token);

        if (username == null) {
            throw new AuthenticationException("认证失败！");
        }

        // 将用户名作为主体（Principal），令牌作为凭据（Credentials）返回
        return new SimpleAuthenticationInfo(username, rawToken, "MyRealm");
    }
}
